<template>
	<view>
		<uv-sticky bgColor="#fff">
			<uv-tabs :list="list" :itemStyle="{'height':'100rpx','padding-left':'15px','padding-right':'15px'}" :activeStyle="{'transform':'scale(1.2)'}" :inactiveStyle="{'transform':'scale(1.1)'}" @click="tabClick" ></uv-tabs>
		</uv-sticky>

		<view class="content">
			<picker @change="handleFromUnitChange" :value="fromUnitIndex" range-key="name"
				:range="currentUnitData.units">
				<view class="unit-name">
					{{currentUnitData.units[fromUnitIndex].name}}{{currentUnitData.units[fromUnitIndex].symbol}}
				</view>
			</picker>
			<input :value="inputValue" type="digit" placeholder="请输入数值" @input="(e)=>{inputValue =e.detail.value,convertUnits()}" />
		</view>

		<view class="change-tip">转换到</view>

		<view class="content">
			<picker @change="handleToUnitChange" :value="toUnitIndex" range-key="name" :range="currentUnitData.units">
				<view class="unit-name">
					{{currentUnitData.units[toUnitIndex].name}}{{currentUnitData.units[toUnitIndex].symbol}}
				</view>
			</picker>
			<input :value="outputValue" type="digit" placeholder="请输入数值" disabled />
		</view>

		<view class="change-info">转换说明</view>
		<view class="change-desc">{{ conversionInfo }}</view>

		<view class="operator">
			<view>最近转换</view>
			<view style="display: flex;align-items: center;">
				<image style="width: 30rpx;height: 30rpx;margin-right: 8rpx;" src="/static/clear.png"></image>
				<view @click="clearHistory">清空</view>
			</view>
		</view>

		<template v-if="conversionHistory.length > 0">
			<view class="content-bw" v-for="(item, index) in conversionHistory" :key="index">
				<view>
					<view>{{ item.value }} {{ item.fromUnit.symbol }}</view>
					<view>= {{ item.result }} {{ item.toUnit.symbol }}</view>
				</view>

				<view style="display: flex;flex-direction: column;align-items: flex-end;">
					<view class="time">{{ item.time }}</view>
					<view class="type-name">{{ unitData[item.type].name }}</view>
				</view>
			</view>
		</template>

		<template v-else>
			<view class="noData">
				<image style="width: 300rpx;height: 300rpx;" src="/static/empty.png"></image>
			</view>
		</template>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		onLoad,
		onShow,
		onReady
	} from '@dcloudio/uni-app'

	// 响应式状态
	const currentUnitType = ref('length');
	const fromUnitIndex = ref(0);
	const toUnitIndex = ref(1);
	const inputValue = ref(1);
	const outputValue = ref('0');
	const conversionInfo = ref('1 米 = 100 厘米');
	const conversionHistory = ref([]);

	const list = [{
		name: "长度",
		type: "length"
	}, {
		name: "重量",
		type: "weight"
	}, {
		name: "时间",
		type: "time"
	}, {
		name: "面积",
		type: "area"
	}, {
		name: "体积",
		type: "volume"
	}, {
		name: "温度",
		type: "temperature"
	}, {
		name: "速度",
		type: "speed"
	}, {
		name: "货币",
		type: "currency"
	}]

	// 单位数据
	const unitData = {
		length: {
			name: "长度",
			units: [{
					name: "毫米",
					symbol: "mm",
					factor: 0.001
				},
				{
					name: "厘米",
					symbol: "cm",
					factor: 0.01
				},
				{
					name: "米",
					symbol: "m",
					factor: 1
				},
				{
					name: "千米",
					symbol: "km",
					factor: 1000
				},
				{
					name: "英寸",
					symbol: "in",
					factor: 0.0254
				},
				{
					name: "英尺",
					symbol: "ft",
					factor: 0.3048
				},
				{
					name: "码",
					symbol: "yd",
					factor: 0.9144
				},
				{
					name: "英里",
					symbol: "mi",
					factor: 1609.344
				}
			]
		},
		weight: {
			name: "重量",
			units: [{
					name: "毫克",
					symbol: "mg",
					factor: 0.000001
				},
				{
					name: "克",
					symbol: "g",
					factor: 0.001
				},
				{
					name: "千克",
					symbol: "kg",
					factor: 1
				},
				{
					name: "吨",
					symbol: "t",
					factor: 1000
				},
				{
					name: "盎司",
					symbol: "oz",
					factor: 0.0283495
				},
				{
					name: "磅",
					symbol: "lb",
					factor: 0.453592
				}
			]
		},
		time: {
			name: "时间",
			units: [{
					name: "毫秒",
					symbol: "ms",
					factor: 0.001
				},
				{
					name: "秒",
					symbol: "s",
					factor: 1
				},
				{
					name: "分钟",
					symbol: "min",
					factor: 60
				},
				{
					name: "小时",
					symbol: "h",
					factor: 3600
				},
				{
					name: "天",
					symbol: "d",
					factor: 86400
				},
				{
					name: "周",
					symbol: "wk",
					factor: 604800
				},
				{
					name: "月",
					symbol: "mo",
					factor: 2628000
				},
				{
					name: "年",
					symbol: "y",
					factor: 31536000
				}
			]
		},
		area: {
			name: "面积",
			units: [{
					name: "平方毫米",
					symbol: "mm²",
					factor: 0.000001
				},
				{
					name: "平方厘米",
					symbol: "cm²",
					factor: 0.0001
				},
				{
					name: "平方米",
					symbol: "m²",
					factor: 1
				},
				{
					name: "公顷",
					symbol: "ha",
					factor: 10000
				},
				{
					name: "平方千米",
					symbol: "km²",
					factor: 1000000
				},
				{
					name: "平方英寸",
					symbol: "in²",
					factor: 0.00064516
				},
				{
					name: "平方英尺",
					symbol: "ft²",
					factor: 0.092903
				},
				{
					name: "平方码",
					symbol: "yd²",
					factor: 0.836127
				},
				{
					name: "英亩",
					symbol: "ac",
					factor: 4046.86
				},
				{
					name: "平方英里",
					symbol: "mi²",
					factor: 2589988.11
				}
			]
		},
		volume: {
			name: "体积",
			units: [{
					name: "立方厘米",
					symbol: "cm³",
					factor: 0.000001
				},
				{
					name: "立方米",
					symbol: "m³",
					factor: 1
				},
				{
					name: "升",
					symbol: "L",
					factor: 0.001
				},
				{
					name: "毫升",
					symbol: "mL",
					factor: 0.000001
				},
				{
					name: "立方英寸",
					symbol: "in³",
					factor: 0.0000163871
				},
				{
					name: "立方英尺",
					symbol: "ft³",
					factor: 0.0283168
				},
				{
					name: "加仑(美)",
					symbol: "gal(US)",
					factor: 0.00378541
				},
				{
					name: "加仑(英)",
					symbol: "gal(UK)",
					factor: 0.00454609
				}
			]
		},
		temperature: {
			name: "温度",
			units: [{
					name: "摄氏度",
					symbol: "°C",
					convertToBase: (v) => v,
					convertFromBase: (v) => v
				},
				{
					name: "华氏度",
					symbol: "°F",
					convertToBase: (v) => (v - 32) * 5 / 9,
					convertFromBase: (v) => v * 9 / 5 + 32
				},
				{
					name: "开尔文",
					symbol: "K",
					convertToBase: (v) => v - 273.15,
					convertFromBase: (v) => v + 273.15
				}
			]
		},
		speed: {
			name: "速度",
			units: [{
					name: "米/秒",
					symbol: "m/s",
					factor: 1
				},
				{
					name: "千米/小时",
					symbol: "km/h",
					factor: 0.277778
				},
				{
					name: "米/分钟",
					symbol: "m/min",
					factor: 0.0166667
				},
				{
					name: "英尺/秒",
					symbol: "ft/s",
					factor: 0.3048
				},
				{
					name: "英里/小时",
					symbol: "mph",
					factor: 0.44704
				},
				{
					name: "节",
					symbol: "kn",
					factor: 0.514444
				}
			]
		},
		currency: {
			name: "货币",
			units: [{
					name: "人民币",
					symbol: "CNY",
					factor: 1
				},
				{
					name: "美元",
					symbol: "USD",
					factor: 7.21
				},
				{
					name: "欧元",
					symbol: "EUR",
					factor: 7.85
				},
				{
					name: "英镑",
					symbol: "GBP",
					factor: 9.12
				},
				{
					name: "日元",
					symbol: "JPY",
					factor: 0.048
				},
				{
					name: "韩元",
					symbol: "KRW",
					factor: 0.0053
				},
				{
					name: "港币",
					symbol: "HKD",
					factor: 0.92
				},
				{
					name: "澳元",
					symbol: "AUD",
					factor: 4.85
				},
				{
					name: "加元",
					symbol: "CAD",
					factor: 5.32
				}
			],
			note: "汇率仅供参考，实时汇率可能有所不同"
		}
	};

	// 计算属性 - 获取当前单位类型的数据
	const currentUnitData = computed(() => {
		return unitData[currentUnitType.value];
	});

	onLoad(() => {
		try {
			const value = uni.getStorageSync('unitHistory');
			if (value) {
				// console.log(value);
				conversionHistory.value = value
			}
		} catch (e) {
			// error
		}

		// 确保目标单位索引有效
		if (currentUnitData.value.units.length <= 1) {
			toUnitIndex.value = 0;
		}

		convertUnits();
	})

	// 点击标签
	function tabClick(e) {
		// console.log(e)
		currentUnitType.value = e.type
	}

	// 监听单位类型变化
	watch(currentUnitType, () => {
		fromUnitIndex.value = 0;
		toUnitIndex.value = currentUnitData.value.units.length > 1 ? 1 : 0;
		convertUnits();
		updateConversionInfo();
	});

	// 处理单位选择变化
	const handleFromUnitChange = (e) => {
		// console.log('handleUnitChange',e)
		fromUnitIndex.value = e.detail.value
		convertUnits();
		updateConversionInfo();
	};

	// 处理单位选择变化
	const handleToUnitChange = (e) => {
		// console.log('handleUnitChange',e)
		toUnitIndex.value = e.detail.value
		convertUnits();
		updateConversionInfo();
	};
	
	// 转换单位
	const convertUnits = () => {
		const value = parseFloat(inputValue.value);

		if (isNaN(value)) {
			outputValue.value = '请输入有效数字';
			return;
		}
		// console.log('fromUnitIndex',fromUnitIndex.value)
		const fromUnitData = currentUnitData.value.units[fromUnitIndex.value];
		const toUnitData = currentUnitData.value.units[toUnitIndex.value];

		let result;

		// 特殊处理温度单位
		if (currentUnitType.value === 'temperature') {
			const baseValue = fromUnitData.convertToBase(value);
			result = toUnitData.convertFromBase(baseValue);
		} else {
			// 其他单位使用因子转换
			result = value * fromUnitData.factor / toUnitData.factor;
		}

		// 使用新的格式化函数处理结果
		  outputValue.value = formatPrecision(result);

		// 添加到历史记录
		addToHistory(value, fromUnitData, toUnitData, parseFloat(outputValue.value));
	};

	// 更新转换信息
	const updateConversionInfo = () => {
		const fromUnitData = currentUnitData.value.units[fromUnitIndex.value];
		const toUnitData = currentUnitData.value.units[toUnitIndex.value];

		let info;

		if (currentUnitType.value === 'temperature') {
			// 温度转换公式
			if (fromUnitData.name === '摄氏度' && toUnitData.name === '华氏度') {
				info = "°C 到 °F: (°C × 9/5) + 32";
			} else if (fromUnitData.name === '华氏度' && toUnitData.name === '摄氏度') {
				info = "°F 到 °C: (°F - 32) × 5/9";
			} else if (fromUnitData.name === '摄氏度' && toUnitData.name === '开尔文') {
				info = "°C 到 K: °C + 273.15";
			} else if (fromUnitData.name === '开尔文' && toUnitData.name === '摄氏度') {
				info = "K 到 °C: K - 273.15";
			} else if (fromUnitData.name === '华氏度' && toUnitData.name === '开尔文') {
				info = "°F 到 K: (°F - 32) × 5/9 + 273.15";
			} else if (fromUnitData.name === '开尔文' && toUnitData.name === '华氏度') {
				info = "K 到 °F: (K - 273.15) × 9/5 + 32";
			} else {
				info = `1 ${fromUnitData.symbol} = 1 ${toUnitData.symbol}`;
			}
		} else {
			// 其他单位转换信息
			let conversionFactor;
			if (fromUnitData.factor && toUnitData.factor) {
				conversionFactor = fromUnitData.factor / toUnitData.factor;
				info = `1 ${fromUnitData.symbol} = ${formatPrecision(conversionFactor)} ${toUnitData.symbol}`;
			} else {
				info = `转换 ${fromUnitData.name} 到 ${toUnitData.name}`;
			}
		}

		// 添加货币类型的备注
		if (currentUnitType.value === 'currency' && currentUnitData.value.note) {
			info += ` | ${currentUnitData.value.note}`;
		}

		conversionInfo.value = info;
	};
	
	// 工具函数：根据数值大小自动保留合适的有效数字
	const formatPrecision = (value) => {
	  // 处理特殊值
	  if (isNaN(value) || value === 0) return '0';
	  
	  const absValue = Math.abs(value);
	  
	  // 根据数值大小动态调整保留的小数位数
	  if (absValue >= 1000) {
	    // 大于等于1000的数，保留0位小数
	    return value.toFixed(0);
	  } else if (absValue >= 100) {
	    // 100-999.99，保留1位小数
	    return value.toFixed(1);
	  } else if (absValue >= 1) {
	    // 1-99.999，保留2位小数
	    return value.toFixed(2);
	  } else if (absValue >= 0.001) {
	    // 0.001-0.999，保留4位小数
	    return value.toFixed(4);
	  } else {
	    // 小于0.001的数，使用科学计数法
	    return value.toExponential(3);
	  }
	};

	// 添加到历史记录
	const addToHistory = (value, fromUnit, toUnit, result) => {
		const timestamp = new Date();
		const historyItem = {
			type: currentUnitType.value,
			value: value,
			fromUnit: fromUnit,
			toUnit: toUnit,
			result: result,
			time: timestamp.toLocaleString()
		};

		// 添加到历史记录数组的开头
		conversionHistory.value.unshift(historyItem);

		// 限制历史记录数量
		if (conversionHistory.value.length > 20) {
			conversionHistory.value.pop();
		}

		// 保存到本地存储
		try {
			uni.setStorageSync('unitHistory', conversionHistory.value);
		} catch (e) {
			// error
		}
	};

	// 清空历史记录
	const clearHistory = () => {
		conversionHistory.value = [];
		try {
			uni.removeStorageSync('unitHistory');
		} catch (e) {
			// error
		}
	};
</script>

<style>
	@import "unit.css"
</style>